package com.linx.adapterdemo

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.linx.simpleadapter.SimpleAdapter
import com.linx.simpleadapter.onClick
import com.linx.simpleadapter.onLongClick
import kotlinx.android.synthetic.main.item_demo.*
import java.util.*

class MainActivity : AppCompatActivity() {

    data class Demo(val title: String, val content: String)

    private val demos by lazy {
        val list = ArrayList<Demo>()
        (0 until 100)
                .map { Demo("item$it", "item content$it") }
                .forEach {
                    list.add(it)
                }
        list
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val rv = RecyclerView(this)
        rv.layoutManager = LinearLayoutManager(this)
        val adapter = SimpleAdapter<Demo>(R.layout.item_demo) {
            //直接使用view id获取view对象
            tv_title.text = it.title
            tv_content.text = it.content
        }.bindEvent {
            onClick(btn) {
                toast("${it.title} position $adapterPosition onClick")
            }
            onLongClick(containerView) {
                AlertDialog.Builder(this@MainActivity)
                        .setItems(arrayOf("删除")) { _, _ ->
                            demos.remove(it)
                            adapter.submitList(demos.copy())
                        }
                        .show()
                true
            }
        }
        rv.adapter = adapter
        adapter.submitList(demos.copy())
        setContentView(rv)
    }

    private fun Context.toast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    private fun <T> List<T>.copy(): List<T> {
        val list = arrayListOf<T>()
        list.addAll(this)
        return list
    }

}